package shun.demo.remote.display.client;

import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import shun.demo.remote.display.model.Movement;
import shun.demo.remote.display.model.Point;
import shun.demo.remote.display.model.Property;
import shun.demo.remote.display.model.TimeSync;
import shun.demo.utils.IOUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

/**
 * Created by chen on 14-5-9.
 */
public class ReceiveThread extends Thread {

    private ObjectInputStream mObjectInputStream;
    private XScreenHandler mXScreenHandler;

    public ReceiveThread(ObjectInputStream ois) {
        super("Client-ReceiveThread");
        mXScreenHandler = XScreenHandler.get();
        mObjectInputStream = ois;
    }

    @Override
    public void run() {
        InputStream is = null;
        try {
            ObjectInputStream ois = mObjectInputStream;

            while (true) {
                try {
                    Object o = ois.readObject();
                    Log.i("ReceiveThread", "from server " + "\n" + o);
                    if (o instanceof Property) {
                        handProperty((Property) o);
                    } else if (o instanceof TimeSync) {
                        handTimeSync((TimeSync) o);
                    } else if (o instanceof Point) {
                        handPoint((Point) o);
                    } else if (o instanceof Movement) {
                        handMovement((Movement)o);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.closeStream(is);
        }
    }

    private void handMovement(Movement movement) {
        Message message = Message.obtain();
        message.what = XScreenHandler.MESSAGE_MOVEMENT;
        message.obj = movement;
        mXScreenHandler.sendMessage(message);
    }

    private void handPoint(Point point) {
        XScreen.get().setScreenLeft(point.getX());
        XScreen.get().setScreenLeftSync(true);
    }

    private void handTimeSync(TimeSync timeSync) {
        long now = SystemClock.uptimeMillis();
        XScreen xScreen = XScreen.get();
        xScreen.setTimeOffset(timeSync.getT1() - now / 2 - timeSync.getT0() / 2);
        xScreen.setLatency((now - timeSync.getT0()) / 2);
        Log.i(XScreen.LOG_TAG, "time offset: " + xScreen.getTimeOffset());
        Log.i(XScreen.LOG_TAG, "latency: " + xScreen.getLatency());
        XScreen.get().setTimeOffsetSync(true);
    }

    private void handProperty(Property p) {
        Message message = Message.obtain();
        message.what = XScreenHandler.MESSAGE_SEND;
        message.obj = p;
        mXScreenHandler.sendMessage(message);
    }
}
